package lib

import (
	"database/sql"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
)


type NullInt32 struct {
	sql.NullInt32
}

// MarshalJSON 序列化为JSON
func (t NullInt32) MarshalJSON() ([]byte, error) {
	if t.Valid {
		return []byte(string(t.Int32)),nil
	}else{
		return []byte("null"),nil
	}

}

// UnmarshalJSON 反序列化为JSON
func (t *NullInt32) UnmarshalJSON(data []byte) error {
	var err error
	// 空值处理
	v := string(data)
	if len(v) ==0 || len(v) == 2 {
		t.Valid = false
	}else{
		t.Valid = true
		v := beego.Substr(v,1,(len(v) - 2))
		result ,e := strconv.ParseInt(v,0,0)
		if e != nil {
			return e
		}else{
			t.Int32 = int32(result)
		}
	}
	return err
}

// String 重写String方法
func (t *NullInt32) String() string {
	data, _ := json.Marshal(t)
	return string(data)
}

// FieldType 数据类型
func (t *NullInt32) FieldType() int {
	return orm.TypeIntegerField

}

// SetRaw 读取数据库值
func (t *NullInt32) SetRaw(value interface{}) error {
	switch value.(type) {
  case int32:
  case int16:
  case int8:
  case int:
    t.Int32 = value.(int32)
	}
	return nil
}

// RawValue 写入数据库
func (t *NullInt32) RawValue() interface{} {
	if t.Valid {
		return t.Int32
	}else{
		return nil
	}
}

